package server;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import server.comm.ClientStub;
import server.comm.ConnectionHandler;
import server.comm.Encoder;
import server.comm.ForumProtocol;
import server.comm.MessageTokenizer;
import server.comm.SimpleEncoder;
import server.comm.Tokenizer;
import utils.LogHelper;
import utils.Settings;

/**
 * @author Alon Segal
 *
 */
public class TcpServer {

	private Settings settings;

	public TcpServer() {
		super();
		settings = new Settings("settings.ini");
		LogHelper.instance().setLogFile(Settings.logFile);
	}

	public void runServer(int port) throws NumberFormatException, IOException {
		Encoder encoder = new SimpleEncoder("UTF-8");
	      ServerSocket socket = new ServerSocket(port);
	      LogHelper.instance().log("Server is running on port "+port);
	      ForumProtocol protocol = new ForumProtocol();
	      while (true) {
	          Socket s = socket.accept();
	          PrintWriter out = new PrintWriter(s.getOutputStream(),true);
	          Tokenizer tokenizer = new MessageTokenizer(new InputStreamReader(s.getInputStream(),encoder.getCharset()),'\0');
	          ClientStub client = new ClientStub(s, "",out,encoder);
	          Runnable connectionHandler = new ConnectionHandler(s, encoder, tokenizer, protocol,client,out);
	          new Thread(connectionHandler).start(); // NOTE HERE: Each connection handler runs in a different thread
	          LogHelper.instance().log("IP " + s.getInetAddress() + " has joined the server.");
	      }
	}
}
